﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QWeiBo.ViewModule;
using QWeiBoN.ViewModule;
using System.Windows.Media.Imaging;
using ImageTools.IO.Gif;
using ImageTools.IO.Png;
using ImageTools.IO.Bmp;
using QWeiBoN.Util;
using System.IO;
using Microsoft.Phone.Tasks;
using TencentWeiboSDK.Model;
using QWeiBoN.Objects;
using Microsoft.Xna.Framework.Input.Touch;

namespace QWeiBoN
{
    public partial class MainPage : PhoneApplicationPage
    {

        private MainListModel mList = new MainListModel();
        private MainUserModel uModel = new MainUserModel();
        private MainMyFansModel fModel = new MainMyFansModel();
        private MainPostNewModel pModel = new MainPostNewModel();
        private AddFriendModel afModel = new AddFriendModel();
        private RepostTextModel rtModel = new RepostTextModel();
        private WeiboCommentsModel wcModel = new WeiboCommentsModel();
        private TextCommentModel tcModel = new TextCommentModel();
        private string source = string.Empty;
        // 图片选择器
        private PhotoChooserTask photoTask = new PhotoChooserTask();
        private BitmapImage imageSource;
        // 点评
        private string commentRoorId = string.Empty;

        /// <summary>
        /// 拉取数据类型
        /// </summary>
        private enum EPollType
        {
            /// <summary>
            /// 默认，结果绑定到控件
            /// </summary>
            Default,
            /// <summary>
            /// 下一页，结果追加到末尾
            /// </summary>
            NextPage,
            /// <summary>
            /// 最新，结果插到开头
            /// </summary>
            Lastest
        }

        /// <summary>
        /// 加载数据的类型
        /// </summary>
        private EPollType pollType { get; set; }

        /// <summary>
        /// 是否正在拉取数据
        /// </summary>
        private bool isPolling { get; set; }

        /// <summary>
        /// 最后一条微博的时间戳
        /// </summary>
        private long lastTimestamp { get; set; }
        /// <summary>
        /// 第一条微博的时间戳
        /// </summary>
        private long firstTimestamp { get; set; }

        /// <summary>
        /// 最后一次刷新的时间
        /// </summary>
        private DateTime lastPollTime { get; set; }

        /// <summary>
        /// 手势是否是垂直拖拽
        /// </summary>
        private bool isVerticalDrag { get; set; }

        public MainPage()
        {
            InitializeComponent();

            pollType = EPollType.Default;
            isPolling = true;

            //this.mainList.DataContext = mList;
            this.CommentsList.DataContext = wcModel;
            wcModel.clearHistory();

            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["mainActionBar"];

            ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
            ImageTools.IO.Decoders.AddDecoder<PngDecoder>();
            ImageTools.IO.Decoders.AddDecoder<BmpDecoder>();
        }

        /// <summary>
        /// 共用的刷新数据的方法
        /// </summary>
        private void Refresh(PageFlag flag, long pagetime)
        {
            isPolling = false;
            lastPollTime = DateTime.Now;
            mList.Refresh(flag, pagetime, (callback) =>
            {
                var newData = new List<Status>();
                callback.Data.ForEach(a =>
                {
                    //a.Nick = a.Nick + "：" + a.Text;
                    DateTime date = new DateTime(1970, 01, 01, 00, 00, 00);
                    date = date.AddSeconds(a.Timestamp);
                    a.From = date.Month + "月" + date.Day + "日 " + date.Hour + ":" + date.Minute + "  " + a.From;
                    if (null == a.Head || a.Head.Equals(""))
                    {
                        a.Head = "Resources/head_50.jpg";
                    }
                    switch (a.Type)
                    {
                        case 2:
                            //a.Nick = a.Nick + " 转播：";
                            a.Nexttime = " 转播：";
                            break;
                        case 3:
                            //a.Nick = a.Nick + " 私信：";
                            a.Nexttime = " 私信：";
                            break;
                        case 6:
                            //a.Nick = a.Nick + " 提及：";
                            a.Nexttime = " 提及：";
                            break;
                        default:
                            //a.Nick = a.Nick + "：";
                            a.Nexttime = "：";
                            break;
                    }
                    newData.Add(a);
                });

                var data = (IEnumerable<Status>)mainList.ItemsSource;
                if (pollType == EPollType.NextPage)
                {
                    data = data.Concat(newData).ToList();
                    //data = newData.Concat(data).ToList();
                }
                else if (pollType == EPollType.Lastest)
                {
                    newData = newData.Where(t => t.Timestamp > firstTimestamp).ToList();
                    if (newData.Count > 0)
                    {
                        data = newData.Concat(data).ToList();
                    }
                }
                else
                {
                    data = newData;
                }
                if (data != null && data.Count() > 0)
                {
                    lastTimestamp = data.LastOrDefault().Timestamp;

                    firstTimestamp = data.FirstOrDefault().Timestamp;
                }
                mainList.ItemsSource = data;
                mainList.UpdateLayout();
            });
        }

        private void RefreshUser()
        {
            uModel.RefreshUser(null);
        }

        private void RefreshFans()
        {
            fModel.RefreshMyFans(null);
        }

        /// <summary>
        /// 窗体加载完毕触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            Refresh(0, 0);
            //RefreshUser();
        }

        /// <summary>
        /// 滚轴视图的选中项改变方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //ApplicationBar = null;
            PivotItem item = (PivotItem)((Pivot)sender).SelectedItem;
            if (item.Header.Equals("微博"))
            {
                ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["mainActionBar"];
            }
            if (item.Header.Equals("个人"))
            {
                this.UserImg.DataContext = uModel;
                this.UserName.DataContext = uModel;
                this.FansNum.DataContext = uModel;
                this.IdolNum.DataContext = uModel;
                this.Tweetnum.DataContext = uModel;
                RefreshUser();
            }
            if (item.Header.Equals("收听"))
            {
                this.fansList.DataContext = fModel;
                RefreshFans();
            }
            if (item.Header.Equals("发表"))
            {
                this.AddGrid.DataContext = pModel;
                ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["addNewBar"];
            }
        }

        /// <summary>
        /// 发送新微博处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            // 以下是处理点击发送新微博的按钮的方法
            pModel.Text = this.NewContext.Text;
            //发送微博，在这里可以提示用户正在发送，或者切换回上一个页面
            pModel.Post(() =>
            {
                // 回调回来后可以通知用户已经发送成功或失败
                // 同时加载最新的微博数据
                //Refresh();
            });
        }

        private void ApplicationBarIconButtonNewImg_Click(object sender, EventArgs e)
        {
            pModel.ChoosePic();
        }

        /// <summary>
        /// 发布新的微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Fans_Button_Click(object sender, RoutedEventArgs e)
        {
            // 这里是处理fans的收听和取消的
            Button button = (Button)sender;
            string openId = button.Tag.ToString();
            if (button.Content.Equals("收听"))
            {
                afModel.addFriend(openId, (callBack) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (null == callBack.InnerException)
                        {
                            button.Content = "取消";
                        }
                        else
                        {
                            MessageBox.Show(callBack.InnerException.Message);
                        }
                    });
                });
            }
            else
            {
                afModel.delFriend(openId, (callBack) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (null == callBack.InnerException)
                        {
                            button.Content = "收听";
                        }
                        else
                        {
                            MessageBox.Show(callBack.InnerException.Message);
                        }
                    });
                });
            }
        }

        // 表示头像图片LeftButtonDown的状态
        bool HeaderLeftButtonDown = false;
        /// <summary>
        /// 头像图片的鼠标按下方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            HeaderLeftButtonDown = true;
        }
        /// <summary>
        /// 头像图片的鼠标抬起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserHeader_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            HeaderLeftButtonDown = false;
            //Image header = sender as Image;
            //string name = header.Tag.ToString();
            //Console.WriteLine(name);
            //if (ShowImg.Visibility == Visibility.Collapsed)
            //{
            //    ShowImg.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    ShowImg.Visibility = Visibility.Collapsed;
            //}
        }

        bool MyTextImgMouseDown = false;

        /// <summary>
        /// 我的内容中的图片的鼠标按下抬起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MyTextImg_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            BigImg.Source = null;
            Image img = sender as Image;
            source = img.Tag.ToString().Replace("160","460");
            Console.WriteLine(source);

            WebClient Client = new WebClient();
            Client.OpenReadCompleted += new OpenReadCompletedEventHandler(Client_OpenReadCompleted);
            Client.OpenReadAsync(new Uri(source, UriKind.Absolute));

            //BitmapImage bitmapImage = new BitmapImage();
            //bitmapImage.UriSource = new Uri(source, UriKind.RelativeOrAbsolute);
            //BigImg.Source = bitmapImage;
            //ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
            //ImageTools.ExtendedImage imgt = new ImageTools.ExtendedImage();
            //imgt.UriSource = new Uri(source, UriKind.RelativeOrAbsolute);
            //BigImg.Source = imgt;
            //if (ShowImg.Visibility == Visibility.Collapsed)
            //{
            //    ShowImg.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    ShowImg.Visibility = Visibility.Collapsed;
            //}
        }
        /// <summary>
        /// Canvas中关闭按钮的点击处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseCanvas_Click(object sender, RoutedEventArgs e)
        {
            MyTextImgMouseDown = false;
            mainList.SelectedItem = null;
            ShowImg.Visibility = Visibility.Collapsed;
        }

        private void SourceImg_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            BigImg.Source = null;
            BigImgJpg.Source = null;
            Image img = sender as Image;
            source = img.Tag.ToString().Replace("160", "460");
            Console.WriteLine(source);

            WebClient Client = new WebClient();
            Client.OpenReadCompleted += new OpenReadCompletedEventHandler(Client_OpenReadCompleted);
            Client.OpenReadAsync(new Uri(source, UriKind.Absolute));
        }

        void Client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream stream = e.Result;

            ImageTypeUtil imgUtil = new ImageTypeUtil();
            if (imgUtil.getImageType(stream) == ImageTypeUtil.ImageType.Jpg)
            {
                BigImgJpg.Visibility = Visibility.Visible;
                BigImg.Visibility = Visibility.Collapsed;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.UriSource = new Uri(source, UriKind.RelativeOrAbsolute);
                BigImgJpg.Source = bitmapImage;
            }
            else
            {
                BigImg.Visibility = Visibility.Visible;
                BigImgJpg.Visibility = Visibility.Collapsed;
                ImageTools.ExtendedImage imgt = new ImageTools.ExtendedImage();
                imgt.UriSource = new Uri(source, UriKind.RelativeOrAbsolute);
                BigImg.Source = imgt;
            }
            if (ShowImg.Visibility == Visibility.Collapsed)
            {
                ShowImg.Visibility = Visibility.Visible;
            }
            else
            {
                ShowImg.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 转发link点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rePostLink_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            string tag = link.Tag.ToString();
            //Console.WriteLine(tag);
            RePostButton.Tag = tag;
            RePostImgSource.Source = null;
            RePostContext.Text = string.Empty;
            ShowRePostDiv.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 关闭转发canvas的按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RePostCancelButton_Click(object sender, RoutedEventArgs e)
        {
            ShowRePostDiv.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 提交转发的转发按钮的处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RePostButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            string text = RePostContext.Text;
            string weiboId = btn.Tag.ToString();
            ShowRePostDiv.Visibility = Visibility.Collapsed;
            rtModel.repostUserText(weiboId, text, imageSource, (callBack) =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //Refresh();
                    MessageBox.Show("微博转播成功");
                });
            });
        }

        /// <summary>
        /// 转发添加图片按钮处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RePostImgButton_Click(object sender, RoutedEventArgs e)
        {
            photoTask.Completed += new EventHandler<PhotoResult>(photoTask_Completed);
            photoTask.Show();
        }

        /// <summary>
        /// 完成图片选择后的处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void photoTask_Completed(object sender, PhotoResult e)
        {
            if (null != e.ChosenPhoto)
            {
                if (null == imageSource)
                {
                    imageSource = new BitmapImage();
                }
                imageSource.SetSource(e.ChosenPhoto);
                RePostImgSource.Source = imageSource;
            }
        }

        /// <summary>
        /// 我的听众列表的行选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fansList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        /// <summary>
        /// 微博显示页的行选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mainList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //ApplicationBar = null;
            if (MyTextImgMouseDown == false)
            {
                if (e.AddedItems.Count > 0)
                {
                    wcModel.clearHistory();
                    Status tmpObjs = e.AddedItems[0] as Status;
                    commentRoorId = tmpObjs.Id;
                    //NavigationService.Navigate(new Uri(string.Format("/UserControler/CommentsList.xaml?{0}={1}&{2}={3}&{4}={5}", AppSetting.CommentsListTypeKey, commentRoorId, AppSetting.CommentsFatherText, tmpObjs.Origtext,AppSetting.CommentFatherName, tmpObjs.Name), UriKind.Relative));
                    NavigationService.Navigate(new Uri(string.Format("/UserControler/WeiboDetailPage.xaml?{0}={1}", AppSetting.CommentsListTypeKey, commentRoorId), UriKind.Relative));
                    //RefreshCommentsList();
                }
            }
        }

        /// <summary>
        /// 共用的点评列表的刷新方法
        /// </summary>
        /// <param name="rootId"></param>
        //private void RefreshCommentsList()
        //{
        //    wcModel.getCommentList(commentRoorId, 1, 30, (callBack) =>
        //    {
        //        Deployment.Current.Dispatcher.BeginInvoke(() =>
        //        {
        //            //WeiboComments.Visibility = Visibility.Visible;
        //            if (mainList.Visibility == Visibility.Visible)
        //            {
        //                mainList.Visibility = Visibility.Collapsed;
        //            }
        //            if (CommentsPanel.Visibility == Visibility.Collapsed)
        //            {
        //                CommentsPanel.Visibility = Visibility.Visible;
        //            }
        //            if (null == ApplicationBar || ApplicationBar.IsVisible == false)
        //            {
        //                ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["addNewCommentBar"];
        //            }
        //        });
        //    });
        //}

        /// <summary>
        /// 微博评论列表applicationbar中的返回按钮的处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            mainList.SelectedItem = null;
            commentRoorId = string.Empty;
            NewComment.Text = string.Empty;
            ApplicationBar = null;
            wcModel.clearHistory();
            //Refresh();
            CommentsPanel.Visibility = Visibility.Collapsed;
            mainList.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 微博评论列表applicationbar中的评论按钮的处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarIconButton_Click_2(object sender, EventArgs e)
        {
            string comText = NewComment.Text;
            if (comText.Trim().Equals(string.Empty))
            {
                MessageBox.Show("评论内容不能为空！");
            }
            else
            {
                tcModel.textComment(comText.TrimEnd(), commentRoorId, (callBack) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //RefreshCommentsList();
                    });
                });
            }
        }

        /// <summary>
        /// 图片按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MyTextImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MyTextImgMouseDown = true;
        }

        /// <summary>
        /// 图片按下事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SourceImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MyTextImgMouseDown = true;
        }

        /// <summary>
        /// 点击人名的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NickLinkButton_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            string tag = link.Tag.ToString();
            uModel.UserId = tag;
            RefreshUser();
            MainPivot.SelectedIndex = 2;
        }

        #region 操作事件

        /// <summary>
        /// 手势结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            if (isVerticalDrag || AppSetting.HightDragSensitivity)
            {
                var scrollviewer = AppSetting.FindChildOfType<ScrollViewer>(mainList);
                if (scrollviewer == null)
                {
                    return;
                }
                //到底部
                if (Math.Abs(scrollviewer.VerticalOffset - scrollviewer.ScrollableHeight) < 2)
                {
                    pollType = EPollType.NextPage;
                    Refresh(PageFlag.Down, lastTimestamp);
                }
                //顶部
                else if (scrollviewer.VerticalOffset < 0.000001)
                {
                    pollType = EPollType.Lastest;
                    Refresh(PageFlag.First, firstTimestamp);
                }
            }
        }
        /// <summary>
        /// 手势开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureBegin(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gs = TouchPanel.ReadGesture();
                if (gs.GestureType == GestureType.VerticalDrag)
                {
                    isVerticalDrag = true;
                }
            }
        }

        /// <summary>
        /// 拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            if (e.Direction.ToString().Equals("Vertical"))
            {
                isVerticalDrag = true;
            }
        }

        #endregion

        /// <summary>
        /// listbox的布局刷新完成方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mainList_LayoutUpdated(object sender, EventArgs e)
        {
            //var data = (IEnumerable<Status>)mainList.ItemsSource;
            //string ddd = "ddd";
        }

        /// <summary>
        /// 添加新微博itembutton点击事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddStatusBtn_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/UserControler/AddStatus.xaml"), UriKind.Relative));
        }

        private void ReloadBtn_Click(object sender, EventArgs e)
        {
            Refresh(0, 0);
        }

        #region 弹出菜单的事件处理

        /// <summary>
        /// 转播menuitem的点击处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Replay(object sender, RoutedEventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            if (null != item)
            {
                Status status = getSelectedMenuStatus(item.Tag.ToString());
                if (null != status)
                {
                    IsoSetting.Set(IsoHelper.FatherStatusKey, status);
                    NavigationService.Navigate(new Uri(string.Format("/UserControler/AddStatus.xaml?{0}={1}", AppSetting.AddStatusTypeKey, (int)AddStatusType.ReAdd.GetHashCode()), UriKind.Relative));
                }
            }
        }

        /// <summary>
        /// 获取弹出菜单所处位置的微博信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private Status getSelectedMenuStatus(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                var listData = (IEnumerable<Status>)mainList.ItemsSource;
                if (null != listData)
                {
                    return listData.Where(t => t.Id == id).FirstOrDefault();
                }
            }
            return null;
        }

        /// <summary>
        /// 返回按钮的处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var tmp = true;
            var rs = MessageBox.Show("确定退出吗？", "提示", MessageBoxButton.OKCancel);
            tmp = rs != MessageBoxResult.Cancel;
            if (tmp)
            {
                App.Quit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        #endregion
        
    }
}